import QtQuick
import QtMultimedia

Item {
    id: playContent
    property double volmue: 1
    property var currentPlayerInfo: ({
            id: 0,
            artists: '',
            name: '',
            coverImage: ''
        })
    property string source: ''
    property string author: currentPlayerInfo.artists
    property string musicName: currentPlayerInfo.name
    property string musicImg: currentPlayerInfo.coverImage
    property alias duration: mediaPlayer.duration
    property alias position: mediaPlayer.position
    property alias playing: mediaPlayer.playing
    //历史播放列表
    property var historyPlayerList: []

    //收藏列表
    property var collectPlayerList: []

    //下一首播放的歌曲信息
    property var nextPlayerInfo: null
    // 播放列表
    property var playerList: []
    // 播放模式： 0 单曲循环 1 顺序播放 2 随机播放
    property int playerModel: 2
    // 播放历史音乐列表的索引
    property int playerhistoryListIndex: -1
    onPlayerModelChanged: {
        playerhistoryListIndex = -1;
    }
    Component.onCompleted: {
        p_db.getValues(["volmue", "playerModel", "currentPlayerInfo", 'playerList', 'collectPlayerList']).then(res => {
            if (res.volmue !== null) {
                volmue = +res.volmue;
                bottomBar.onRealVolumeChange(volmue);
            }
            if (res.playerModel !== null)
                playerModel = +res.playerModel;
            if (res.collectPlayerList !== null)
                collectPlayerList = JSON.parse(res.collectPlayerList);
            if (res.currentPlayerInfo !== null) {
                currentPlayerInfo = JSON.parse(res.currentPlayerInfo);
                _loadUrl();
                pushHistory();
            }
            if (res.playerList !== null)
                playerList = JSON.parse(res.playerList);
        });
    }
    Component.onDestruction: {
        p_db.setValues({
            volmue: volmue,
            playerModel: playerModel,
            currentPlayerInfo: currentPlayerInfo,
            playerList: playerList,
            collectPlayerList: collectPlayerList
        });
        // p_db.setValue("volmue",`${volmue}`)
        // p_db.setValue("playerModel",`${playerModel}`)
        // p_db.setValue("currentPlayerInfo",JSON.stringify(currentPlayerInfo))
        // if(playerList.length>0)
        //     p_db.setValue("playerList",JSON.stringify(playerList))
    }
    function _loadUrl() {
        return p_musicRes.getMusicUrl(currentPlayerInfo.id).then(url => {
            if (url === null) {
                toast.show("音乐资源不存在");
                return false;
            }
            playSources = url;
            return true;
        });
    }

    function pushHistory() {
        if (playerhistoryListIndex == -1 && currentPlayerInfo.id !== 0) {
            historyPlayerList = historyPlayerList.filter(i => i.id !== currentPlayerInfo.id);
            historyPlayerList.push(currentPlayerInfo);
        }
    }

    function requestPlay(musicInfo, _playerList) {
        if (_playerList)
            playerList = _playerList;
        if (musicInfo && musicInfo.id === currentPlayerInfo.id) {
            if (mediaPlayer.playing) {
                toast.show("正在播放");
            } else {
                mediaPlayer.play();
            }
            return;
        }
        currentPlayerInfo = musicInfo || currentPlayerInfo;
        if (musicInfo) {
            playerhistoryListIndex = -1;
        }
        _loadUrl().then(f => {
            if (!f)
                return;
            pushHistory();
            mediaPlayer.play();
        });
    }
    //播放下一首
    function requestNextPlay() {
        if (nextPlayerInfo !== null) {
            currentPlayerInfo = nextPlayerInfo;
            nextPlayerInfo = null;
            requestPlay();
            return;
        }
        if (playContent.playerModel != 0 && playerhistoryListIndex !== -1) {
            if (historyPlayerList.length > playerhistoryListIndex + 1) {
                playerhistoryListIndex += 1;
                currentPlayerInfo = historyPlayerList[playerhistoryListIndex];
                requestPlay();
                return;
            } else {
                playerhistoryListIndex = -1;
            }
        }
        switch (playContent.playerModel) {
        case 0 //单曲循环
        :
            position = 0;
            mediaPlayer.play();
            break;
        case 1 //顺序播放
        :
            if (playerList.length == 0) {
                position = 0;
                requestPlay();
                return;
            }
            let index = 0;
            for (let i = 0; i < playerList.length; i++) {
                if (currentPlayerInfo.id === playerList[i].id) {
                    index = (i === playerList.length - 1) ? 0 : (i + 1);
                    break;
                }
            }
            currentPlayerInfo = playerList[index];
            requestPlay();
            break;
        case 2:
            if (playerList.length <= 1) {
                position = 0;
                requestPlay();
                return;
            }
            const index2 = Math.floor(Math.random() * playerList.length);
            if (currentPlayerInfo !== null && playerList[index2].id === currentPlayerInfo.id) {
                requestNextPlay();
                return;
            }
            currentPlayerInfo = playerList[index2];
            requestPlay();
            break;
        }
    }

    //播放上一首
    function requestPrePlayer() {
        if (historyPlayerList.length <= 1 || playerhistoryListIndex == 0) {
            toast.show("没有上一首");
            return;
        }
        if (playerhistoryListIndex === -1) {
            if (currentPlayerInfo.id === historyPlayerList[0].id) {
                toast.show("没有上一首");
                return;
            }
            playerhistoryListIndex = historyPlayerList.length - 1;
            if (currentPlayerInfo !== null && historyPlayerList[playerhistoryListIndex].id === currentPlayerInfo.id) {
                if (playerhistoryListIndex > 1) {
                    playerhistoryListIndex--;
                } else {
                    toast.show("没有上一首");
                    return;
                }
            }
        } else {
            playerhistoryListIndex--;
        }
        currentPlayerInfo = historyPlayerList[playerhistoryListIndex];
        requestPlay();
    }

    function requestPlayOrStop() {
        if (mediaPlayer.playing) {
            mediaPlayer.pause();
        } else {
            if (source == '') {
                requestPlay();
            } else {
                mediaPlayer.play();
            }
        }
    }

    function pushNextPlayer(playerInfo) {
        nextPlayerInfo = playerInfo;
        playerhistoryListIndex = -1;
    }
    //是否存在收藏
    function hasCollect(id) {
        if (!id) {
            id = currentPlayerInfo.id;
        }
        for (let item of collectPlayerList) {
            if (item.id === id) {
                return true;
            }
        }
        return false;
    }
    function collectMusic(playerInfo) {
        if (!playerInfo) {
            playerInfo = currentPlayerInfo;
        }
        collectPlayerList.unshift(playerInfo);
        collectPlayerList = collectPlayerList;
    }
    function unCollectMusic(id) {
        if (!id) {
            id = currentPlayerInfo.id;
        }
        collectPlayerList = collectPlayerList.filter(item => item.id !== id);
    }
    MediaDevices {
        id: devices
        onDefaultAudioOutputChanged: {
            if (defaultAudioOutput.description.indexOf("耳机") === -1) {
                if (mediaPlayer.playing) {
                    mediaPlayer.pause();
                }
            }
        }
    }
    MediaPlayer {
        id: mediaPlayer
        source: playSources
        audioOutput: AudioOutput {
            device: devices.defaultAudioOutput
            volume: playContent.volmue
        }
        onPlayingChanged: {
            // bottomBar.player = playing
            if (!(!playing && position == duration)) {
                return;
            }
            //播放结束
            playContent.requestNextPlay();
        }
    }
}
